#include <gtk/gtk.h>   
#include <gst/gst.h>   
#include <signal.h>   
#include <string.h>   
#include <gst/interfaces/xoverlay.h>
#include <gdk/gdkx.h>
#include <dirent.h>
#include <unistd.h>

#include "config.h"
#include "mp4_player.h"
#include "sys_log.h"

static GstElement *pipeline, *source, *sink;  
static GMainLoop *mainloop = NULL;    
static GtkWidget *video_window;
static char  file[100][1024];
static int file_index=0;
static int file_count=0;

static gboolean bus_call(GstBus *bus,GstMessage *msg,gpointer data)  
{  
    GMainLoop *loop=data;  
    switch (GST_MESSAGE_TYPE(msg))  
    {  
    case GST_MESSAGE_EOS:  
        SYS_LOG("End-of_stream");
		player_play_next();
        break;  
    case GST_MESSAGE_ERROR:  
    {  
        gchar *debug;  
        GError *err;  
        gst_message_parse_error(msg,&err,&debug);  
        g_free(debug);  
        SYS_LOG("Error: %s",err->message);  
        g_error_free(err);  
        break;  
    }  
    default:  
        break;  
    }  
    return TRUE;  
}  

static gboolean expose_cb(GtkWidget *widget,GdkEventExpose *event,gpointer data)
{
	//gst_x_overlay_set_xwindow_id(GST_X_OVERLAY(data),GDK_WINDOW_XWINDOW(widget->window));
	return FALSE;
}

GstElement *create_player(char *pFilePath)	
{
	GError *error  = NULL;
    GstBus *bus;  

	if(!pFilePath) {
		SYS_LOG("create_player path null");
		return NULL;
	}

	char *pSourcePath = g_strdup_printf("filesrc name=testsrc location=%s ! qtdemux name=demux demux.audio_00 ! queue ! decodebin ! volume ! pulsesink demux.video_00 ! queue ! decodebin ! xvimagesink name=testsink",pFilePath);
	pipeline = gst_parse_launch(pSourcePath,&error);

	if(!pipeline) {
		SYS_LOG("create_player failed");
		return NULL;
	}

	bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));  
    gst_bus_add_watch(bus,bus_call,mainloop);  
    gst_object_unref(bus);
	
	source = gst_bin_get_by_name(GST_BIN(pipeline), "testsrc");
	sink = gst_bin_get_by_name(GST_BIN(pipeline), "testsink");
	if(NULL == source) {
		SYS_LOG("source failed");
	}
	if(NULL == sink) {
		SYS_LOG("sink failed");
	}
	gst_x_overlay_set_xwindow_id(GST_X_OVERLAY(sink),GDK_WINDOW_XID(gtk_widget_get_window(video_window)));
	gst_element_set_state(pipeline,GST_STATE_PLAYING);
	return pipeline;
}

void player_play_next()
{
	player_stop();
	//SYS_LOG("player_play_next[%d][%d]\n",file_index,file_count);
	if(file_index == file_count-1){
		file_index = 0;
	} else {
		file_index++;
	}
	//SYS_LOG("player_play_next[%d][%s]\n",file_index,file[file_index]);
	create_player(file[file_index]);
}
void player_play_mp4(GtkWidget* window)
{
	if(NULL == window) {
		SYS_LOG("player_play_mp4 failed\n");
		return;
	}
	video_window = window;
	create_player(file[file_index]);
}

void player_play_mp4_set_loop(GMainLoop *loop)
{
	mainloop = loop;
}

void player_stop()  
{   
    SYS_LOG("stop was pressed\n");  
    gst_element_set_state(pipeline,GST_STATE_NULL);  
   	gst_object_unref(GST_OBJECT(pipeline));
	pipeline = NULL;
	source = NULL;
	sink = NULL;
	mainloop = NULL;
}  

void player_pause()  
{   
    gst_element_set_state(pipeline,GST_STATE_PAUSED);  
}  

void player_continue()  
{   
    gst_element_set_state(pipeline,GST_STATE_PLAYING);  
}  

int player_read_filelist()
{
    DIR *dir;
    struct dirent *ptr;
    char base[1000];
	int i = 0;

	memset(base,'\0',sizeof(base));
	getcwd(base, 999);

	strcat(base,MP4_PATH);
	
    if ((dir=opendir(base)) == NULL)
    {
        SYS_LOG("Open dir error...");
        exit(1);
    }
	file_count = 0;
    while ((ptr=readdir(dir)) != NULL)
    {
        if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0)    ///current dir OR parrent dir
            continue;
        else if(ptr->d_type == 8) {    ///file
			if(g_strrstr(ptr->d_name,".mp4")) {//store
				memset(file[i],0,1024);
				sprintf(file[i],"%s/%s",base,ptr->d_name);
				 SYS_LOG("file[%d]:%s\n",i,file[i]);
				i++;
				file_count++;
			}
		}
        else if(ptr->d_type == 10)    ///link file
            SYS_LOG("d_name:%s/%s\n",base,ptr->d_name);
     }
     closedir(dir);
     return 1;
}

